package org.lq.us.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.lq.us.commons.Page;
import org.lq.us.dao.RoelDao;
import org.lq.us.entity.Role;import org.lq.us.entity.Users;
import org.lq.us.util.JDBCUtils;

public class RoelDaoImpl extends JDBCUtils implements RoelDao {
	
	
	@Override
	public int save(Role r) {
		try {
			return queryRunner.update("insert into role(rname,rdesc)values(?,?)",r.getRname(),r.getRdesc());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int deltet(int id) {
		try {
			return queryRunner.update("delete from role where id = ?",id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public Role getById(int id) {
		try {
			return queryRunner.query("select * from role where id=?", new BeanHandler<Role>(Role.class),id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public int update(Role r) {
		try {
			return queryRunner.update("update role set rname=? , rdesc=? where id = ?",r.getRname(),r.getRdesc(),r.getId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public void findPage(Page<Role> page, String name) {
		try {
			
			List<Role> list =queryRunner.query("select * from role where rname like ? order by "+page.getFieldName()+ " "+page.getOrderType()+" limit ?,?", new BeanListHandler<Role>(Role.class),"%"+name+"%",page.getStartIndex(),page.getPageSize());
			page.setList(list);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public int getCount(String name) {
		try {
			return queryRunner.query("select count(1) from role where rname like ?", new ScalarHandler<Long>(),"%"+name+"%").intValue();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int getUserCountByRid(int rid) {
		try {
			return queryRunner.query("select count(1) from users where rid = ?", new ScalarHandler<Long>(),rid).intValue();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public List<Map<String, Object>> getPieData() {
		String sql = "select rname name,(select count(1) from users where rid = r.id) value from role r";
		try {
			return queryRunner.query(sql, new MapListHandler());
		} catch (SQLException e) {
			e.printStackTrace();
		};
		return null;
	}

}
